package com.hjs.mr.merge_and_sort;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * SortMapper继承了Mapper接口，泛型的输入是根据InputFormat定义的类型一致
 */
public class SortMapper extends Mapper<Text, BytesWritable, SortBean, NullWritable> {

    @Override
    protected void map(Text key, BytesWritable value, Context context) throws IOException, InterruptedException {
        //将读取来的数据的值得内容进行处理，此处读取过来的是经过InputFormat处理过的value
        String lineData = new String(value.getBytes());
        lineData = lineData.replace("\r","");//除去用不到的字符
        String[] lines = lineData.split("\n");//进行分割，分割结果是一个一个字符串格式的数字
        for (String line : lines) {//遍历切分之后的字符串，将每个数字写入到一个实体中区，并用context.write写出，之后会进入到Reducer进行处理
            if (StringUtils.isNotEmpty(line.trim())) {
                int number = Integer.parseInt(line.trim());
                SortBean sortBean = new SortBean(number);
                context.write(sortBean, NullWritable.get());
            } else//无法处理的数据将其返回null
                context.write(null, NullWritable.get());
        }
    }
}
